package quesGenerate;

import java.util.Random;

public class quesStringGenerate {
    boolean neg;    //是否有负数
    char[] chars;   //运算符号
    int status;     //符号状态
    int range;  //运算范围
    public quesStringGenerate() {
        neg = false;
        chars = new char[]{'+','-','*','/'};
        range = 100;
        status = 31;
    }
    // 运算生成函数，接口往下翻捏
    public String generateQues() {
        int a=0 ,b=0;
        int res=0;
        int op = generateOp();
        // 通过运算符计算结果 注意取任意值范围不能为负数
        Random random = new Random();
        switch (op) {
            case 0:
                res = generateNum()+1;
                if(res == 0) res = 10;
                a = random.nextInt(Math.abs(res));
                b = res - a;
                break;
            case 1:
                a = generateNum()+1;
                if(a == 0) a = 10;
                b = random.nextInt(Math.abs(a));
                res = a-b;
                break;

            // 加减号问题
            case 2:
                res = generateNum()+1;
                if(res == 0) res += 10;
                a = random.nextInt(Math.abs(res))+1;
                b = res/a; res = a*b;
                break;

            // 生成答案概率有问题捏
            case 3:
                a = generateNum();
                b = generateNum();
                b = b==0?b+10:b;
                res = a/b;
                break;

            default: res = -1; break;
        }

        //初始化问题字符串
        String stringQues = new String();
        stringQues += (Integer.toString(a) + String.valueOf(chars[op]) + Integer.toString(b)+"=");
        //填充至12
        while(stringQues.length() < 12) {
            stringQues+=" ";
        }
        stringQues += Integer.toString(res);
        return stringQues;
    }
    // 生成符合规则的数字
    private int generateNum() {
        Random r = new Random();
        // 正负号判断
        if(!neg || r.nextInt(2) == 1)
            return r.nextInt(range);
        else
            return -r.nextInt(range);
    }
    // 生成可选的运算符/chars数组下标
    private int generateOp() {
        Random random = new Random();
        int idx;
        do {
            idx = random.nextInt(4);
        } while ((status & 1<<idx) != 1<<idx);
        return idx;
    }


    // 修改参数接口函数
    // 设置是否出现负数
    public void setNeg(boolean neg) {
        this.neg = neg;
    }
    // 设置是否计算符号 一个二进制 运算符chars  -> 1<<idx 多位加一起
    public void setChars(int status) {
        this.status = status;
    }
    // 设置计算范围   最高四位数 否则返回false
    public boolean setRange(int range) {
        if(range>9999)
            return false;
        else
            this.range = range+1;
        return true;
    }
}
